package com.controller;

import com.alibaba.fastjson.JSON;
import com.entity.User;
import com.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Test {
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();

            // selectOne
            {
//                User user = sqlSession.selectOne("mapper.UserMapper.selectUser");

                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                User user = userMapper.selectUser();

                System.out.println(JSON.toJSONString(user));
            }

//            // selectList
//            {
//                List<User> listUsers = sqlSession.selectList("mapper.UserMapper.selectUsers");
//                System.out.println(JSON.toJSONString(listUsers));
//            }

            // insert
//            {
//                User user = new User();
//                user.setCode("2023003");
//                user.setName("周杰伦");
//                sqlSession.insert("mapper.UserMapper.insertOne", user);
//                System.out.println(JSON.toJSONString(user));
//
//                sqlSession.commit();
//            }

//            // update
//            {
//                User user = sqlSession.selectOne("mapper.UserMapper.selectUser");
//                user.setName(user.getName() + "2");
//                sqlSession.update("mapper.UserMapper.updateOne", user);
//                System.out.println(JSON.toJSONString(user));
//
//                sqlSession.commit();
//            }

            // delete
//            {
//                sqlSession.delete("mapper.UserMapper.deleteOne");
//                System.out.println("delete------finish");
//
//                sqlSession.commit();
//            }

            // 释放资源
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
